#include"string2.h"
#include<stdio.h>
#include<stdlib.h>

#define min(x,y) ((x)<(y)?(x):(y))

int lenofarr(char *str){
	int i=0;
	if(!str){
		return error;
	}
	while(*(str+i)!='\0'){
		i++;
	}
	return i;
}

status init(string *s,int maxlength,char *str){
	int i=0;
	s->str=(char*)malloc(sizeof(char)*maxlength);
	if(!(s->str)) exit(overflow);
	s->maxlength=maxlength;
	if(str!=NULL){
		while(i<maxlength && *(str+i)!='\0'){
			s->str[i]=str[i];
			i++;
		}
	}
	s->length=i;
	return ok;
}
status assign(string *s,string *t){
	if(s->maxlength<t->length){
		return error;
	}
	for(int i=0;i<t->length;i++){
		s[i]=t[i];
	}
	s->length=t->length;
	return ok;
}
status length(string *s){
	return s->length;
}
status cmp(string *s,string *t){
	int res,i;
	int minlen=min(s->length,t->length);
	for(i=0;i<minlen;i++){
		if((res=*(s->str+i)-*(t->str+i))!=0){
			return res;
		}
	}
	if(*(s->str+i)!='\0'){
		return true;
	}else{
		return false;
	}
}
status insert(string *s,int pos,string *t){
	int i;
	if(pos<0){return error;}
	if(s->length+t->length>s->maxlength){
		realloc(s->str,(s->length+t->length)*sizeof(char));
		s->maxlength=s->length+t->length;
	}
	for(i=s->length+t->length-1;i>=pos+t->length;i--){
		s->str[i]=s->str[i-t->length];
	}
	for(i=0;i<t->length;i++){
		s->str[pos+i]=t->str[i];
	}
	s->length+=t->length;
	return ok;
}

status del(string *s,int pos,int len){
	if(pos<0 || len<0 || pos+len>s->length){
		return 0;
	}
	for(int i=pos+len;i<=s->length-1;i++){
		s->str[i-len]=s->str[i];
	}
	s->length-=len;
	return ok;
}

status substring(string *s,int pos,int len,string *t){
	if(pos<0 || len<0 || pos+len>s->length){
		return error;
	}
	if(len>t->maxlength){
		realloc(t->str,(len)*sizeof(char));
		t->maxlength=len;
	}
	for(int i=0;i<len;i++){
		t->str[i]=s->str[pos+i];
	}
	t->length=len;
	return ok;
}

status search(string *s,int start,string *t){
	return ok;
}

status replace(string *s,int start,string *t,string *v){
}

status destroy(string *s){
	free(s->str);
	s->maxlength=0;
	s->length=0;
}
void showstr(string *s){
	for(int i=0;i<s->length;i++){
		printf("%c",s->str[i]);
	}
	printf("\n");
	printf("the length is:%d\n",length(s));
}
int main(){
	string my1,my2,my3;
	int i,max1=5,max2=9,max3=0;
	init(&my1,max1,"data");
	init(&my2,max2,"structure");
	init(&my3,max3,"");
	showstr(&my1);
	showstr(&my2);
	showstr(&my3);
//	assign(&my2,&my1);
//	showstr(&my2);
	printf("%d\n",cmp(&my1,&my2));
	insert(&my2,9,&my1);
	showstr(&my2);

	destroy(&my1);
	destroy(&my2);
	destroy(&my3);
}
